package com.cs.controller;


import com.cs.pojo.Drug;
import com.cs.resultVO.ResultVO;
import com.cs.service.DrugService;
import com.cs.util.ExcelUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping ("/drug")
@ResponseBody
public class DrugController {
    
    @Resource
    private DrugService drugService;
    
    //所有药物
    @RequestMapping(value = "all" , method = RequestMethod.GET)
    public ResultVO<Drug> queryByAll(){
        return new ResultVO<>(drugService.queryAll());
    }


    //药物列表
    @RequestMapping(value = "list" , method = RequestMethod.GET)
    public ResultVO<Drug> queryByPage(Drug drug,Integer pageNum){
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageNum<0 || pageNum>100){
            pageNum = 1;
        }
        System.out.println("drug : " + drug);
        System.out.println("pageNum : " + pageNum);
        PageInfo<Drug> drugs = drugService.queryByPage(3 , pageNum , drug);
        return new ResultVO<>(drugs);
    }
    
    //获取药物
    @RequestMapping(value = "{drId}",method = RequestMethod.GET)
    public ResultVO<Drug> queryById(@PathVariable("drId") Integer drId){
        return new ResultVO<>(drugService.queryById(drId));
    }
    
    //更新药物
    @RequestMapping(value = "",method = RequestMethod.PUT)
    public ResultVO<Drug> update(Drug drug){
        // System.out.println("drug : " + drug);
        int update = drugService.update(drug);
        if (update == 0){
            new ResultVO<>(500 , "检查填写的数据！");
        }
        return new ResultVO<>();
    }
    
    //新增药物
    @RequestMapping(value = "",method = RequestMethod.POST)
    public ResultVO<Drug> add(Drug drug){
        int add = drugService.add(drug);
        if (add == 0){
            return new ResultVO<>(500,"填写信息有误！");
        }
        return new ResultVO<>();
    }
    

    //添加库存
    @RequestMapping(value = "{drNum}",method = RequestMethod.PUT)
    public ResultVO<Drug> drNumAdd(@PathVariable("drNum") Integer drNum, Integer drId){
        Drug drug = drugService.queryById(drId);
        if (drNum > 0){
            drug.setDrNumber(drug.getDrNumber()+drNum);
        }
        int update = drugService.update(drug);
        if (update == 0){
            new ResultVO<>(500 , "检查填写的数据！");
        }
        return new ResultVO<>();
    }
    
    
    /** 图片上传
     *  参考文章 ： https://www.cnblogs.com/yxmhl/p/11617497.html
     */
    @RequestMapping(value = "uploadImage",method = RequestMethod.POST)
    public ResultVO<Drug> uploadImage(
            @RequestParam ("file") MultipartFile file,
            @RequestParam ("drId") Integer drId,
            HttpServletRequest request) throws IOException {
        
        // 文件路径及文件名称
        String path = request.getServletContext().getRealPath("/Images/uploadFile/drug/");
        // 随机生成
        String randomName = UUID.randomUUID().toString().replace("-","");
        // 文件原始名称
        String fileName = file.getOriginalFilename();
        if (fileName == null){
            return new ResultVO<>(500,"上传文件不符合条件！");
        }
        // 获取文件后缀
        int index = fileName.lastIndexOf(".");
        String hz = fileName.substring(index);
        //限制文件类型(后缀)
        switch (hz){
            case ".jpg":
            case ".JPG":
                hz = ".jpg";break;
            case ".png":
            case ".PNG":
                hz = ".png";break;
            default:
                return new ResultVO<>(500,"上传文件不符合条件！");
        }
        // 新 图片文件名 拼接
        String newFileName = randomName + hz;
        
        try {
            //将接收到的文件传输到给定的目标文件
            file.transferTo(new File(path+"/"+newFileName));
            
            System.out.println("上传成功！"+path+"/"+newFileName);
            
            //将图片 新名称 存储至数据中
            Drug drug = drugService.queryById(drId);
    
            //删除原旧的文件（静态图片资源）
            String oldFileName = drug.getDrUrl();
            if (oldFileName != null){
                boolean delete = new File(path + "/" + oldFileName).delete();
                if (!delete){
                    return new ResultVO<>(500,"图片处理异常！请联系管理员！");
                }
            }
            drug.setDrUrl(newFileName);
            int tmp = drugService.update(drug);
            if (tmp == 1){
                return new ResultVO<>();
            }else{
                return new ResultVO<>(500,"服务器异常！请销后再试！");
            }
            
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVO<>(500,"图片上传异常！"+e.getMessage());
        }
    }
    
    /** 生成 Excel
     *  参考文章 ： https://www.cnblogs.com/libo0125ok/p/8026779.html
     */
    @RequestMapping(value = "/excel" , method = RequestMethod.GET)
    public void exportExcelDrug(ServletResponse resp) throws IOException{
    
        // Excel文件名称
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String formatTime = sdf.format(d);
        String fileName = "药物表 - "+formatTime;
        
        // 填充数据
        // 主要列表内容
        List<Map<String,Object>> list = createExcelRecord(drugService.queryAll());
        // 列名
        String[] columnNames = {
                "药物编号","图片名","进货价","出售价","药物名","药物类型","药物介绍","保质期","详细描述","厂家","服用说明","库存","备注"
        };
        // map 中的 key
        String[] keys = {
                "drId", "drUrl", "drInprice", "drOutprice", "drName", "drType", "drSimdesc", "drExpirationdate", "drDetadesc", "drFactory", "drDirection", "drRemark", "drNumber"
        };
    
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        try {
            ExcelUtil.createWorkBook(list , keys , columnNames).write(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        
        // 设置response参数，可以打开下载页面
        HttpServletResponse res = (HttpServletResponse) resp;
        res.reset();
        res.setContentType("application/vnd.ms-excel;charset=utf-8");
        res.setHeader("Content-Disposition",
                "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), StandardCharsets.ISO_8859_1));
        ServletOutputStream out = res.getOutputStream();
        try (BufferedInputStream bis = new BufferedInputStream(is) ;
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff , 0 , buff.length))) {
                bos.write(buff , 0 , bytesRead);
            }
        }
        
    }
    
    /**
     * 生成 Excel 数据形式
     * @param drList 数据列表
     * @return Excel 数据形式
     */
    private List<Map<String, Object>> createExcelRecord(List<Drug> drList) {
        
        List<Map<String , Object>> listMap = new ArrayList<>();
        
        // 工作表命名 (默认‘sheet1’)
        Map<String , Object> firstMap = new HashMap<>();
        firstMap.put("sheetName" , "sheet1");
        listMap.add(firstMap);
        
        //记录数据
        
        for (Drug drug : drList) {
            
            Map<String, Object> map = new HashMap<>();
            //严格遵守写入顺序
            map.put("drId" , drug.getDrId());
            map.put("drUrl" , drug.getDrUrl());
            map.put("drInprice" , drug.getDrInprice());
            map.put("drOutprice" , drug.getDrOutprice());
            map.put("drName" , drug.getDrName());
            String drType = drug.getDrType();
            switch (drType) {
                case "1": drType = "中药";break;
                case "2": drType = "西药";break;
                case "3": drType = "处方";break;
                default:
                    drType = "未分配类型";break;
            }
            map.put("drType" , drType);
            map.put("drSimdesc" , drug.getDrSimdesc());
            map.put("drExpirationdate" , drug.getDrExpirationdate());
            map.put("drDetadesc" , drug.getDrDetadesc());
            map.put("drFactory" , drug.getDrFactory());
            map.put("drDirection" , drug.getDrDirection());
            map.put("drRemark" , drug.getDrRemark());
            map.put("drNumber" , drug.getDrNumber());
        
            listMap.add(map);
        }
        
        return listMap;
    }
    
}

